package com.qf.smsplatform.strategy.strategy.Impl;

import com.qf.smsplatform.common.constants.CacheConstants;
import com.qf.smsplatform.common.constants.StrategyConstants;
import com.qf.smsplatform.common.model.StandardSubmit;
import com.qf.smsplatform.strategy.client.CacheClient;
import com.qf.smsplatform.strategy.strategy.Strategy;
import com.qf.smsplatform.strategy.util.PushErrorMessageUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * projectName: smsplatform
 *
 * @author: MaTianWei
 * time: 2021/8/12 20:58
 * description:1小时限流策略校验
 */
@Service(value = "limitOneHour")
@Slf4j
public class LimitOneHourStrategyImpl implements Strategy {

    @Autowired
    private CacheClient cacheClient;

    @Override
    public boolean execute(StandardSubmit submit) {
        log.info("[策略模块-1小时限流策略校验] =====开始执行=====");
        //1.封装key LIMIT:ClientID:Mobile
        String key = CacheConstants.CACHE_PREFIX_SMS_LIMIT + submit.getClientID() + ":" + submit.getDestMobile();
        int count = cacheClient.zRangeByScore(key, System.currentTimeMillis() - 1440 * 60 * 1000, System.currentTimeMillis());
        //短信发送成功后记录短信发送的时间+手机号
        if (count >= 10) {
            //五分钟内已经有10条了,不能发
            PushErrorMessageUtil.sendLog(submit, StrategyConstants.STRATEGY_ERROR_BLACK);
            PushErrorMessageUtil.sendReport(submit, StrategyConstants.STRATEGY_ERROR_BLACK);
            log.info("[策略模块-1小时限流策略校验] =====执行失败=====");
            return false;
        }
        log.info("[策略模块-1小时限流策略校验] =====执行成功=====");
        return true;
    }
}
